<?php

require_once 'Basic.php';

class ClientCreate extends BasicEntity {
  
  private static $actionName = "Create";
  
  private static $emailField = 'email';
  private static $passwordField = 'password';
  private static $clientTypeField = "clientType";
  private static $documentField = "document";
  private static $nameField = "name";
  
  private static $userTypes = array(
      "fisica" => "Pessoa Física",
      "juridica" => "Pessoa Jurídica"
  );
  
  public function __construct() {
    $this->fields = array(
        new FormField(true, ClientCreate::$nameField, "Nome/Raz&atilde;o Social", new FormFieldTextLine()),
        new FormField(true, ClientCreate::$clientTypeField, "Tipo", new FormFieldChoice(ClientCreate::$userTypes)),
        new FormField(true, ClientCreate::$documentField, "CPF/CNPJ", new FormFieldTextLine()),
        new FormField(true, ClientCreate::$emailField, 'Email', new FormFieldEmail()),
        new FormField(true, ClientCreate::$passwordField, "Senha", new FormFieldPassword())
    );
    $this->processFields();
  }
  
  public function actionDescription() {
    return ClientCreate::$actionName;
  }
  
  public function actionCreate($userInput) {
    foreach($this->fields as $k => $v) {
      $$k = $v->value();
    }
    
    $out = "";
    
    switch($clientType) {
      case "fisica":
        $out = FormFieldCPF::validateCpf($document);
        if($out !== true) {
          goto invalidDocument;
        }
        break;
      case "juridica":
        $out = FormFieldCNPJ::validateCnpj($document);
        if($out !== true) {
          goto invalidDocument;
        }
        break;
    }
    
    $db = new DBUtils();
    
    try {
      $db->connect();
      
      $db->runQuery("select idCliente from Cliente where email = ?", array($email));
      if($db->getItem() !== null) {
        $this->fields[ClientCreate::$emailField]->setValid(false);
        return "Usu&aacute;rio com email ${email} j&aacute; cadastrado.";
      }
      
      $db->beginTransaction();
      $db->runQuery("insert into Endereco (uf) values (null)");
      $db->runQuery("select IDENT_CURRENT('Endereco') as idEndereco");
      $idEndereco = $db->getItem()->idEndereco;
      $db->runQuery("insert into Cliente (email, senha, tipo, endereco) values(?, ?, ?, ?)",
              array($email, $password, $clientType, $idEndereco));
      $db->runQuery("select IDENT_CURRENT('Cliente') as idCliente");
      $idCliente = $db->getItem()->idCliente;
      
      switch($clientType) {
        case "fisica":
          $db->runQuery("insert into PessoaFisica (idCliente, cpf, nome) values(?, ?, ?)",
              array($idCliente, $document, $name));
          break;
        case "juridica":
          $db->runQuery("insert into PessoaJuridica (idCliente, cnpj, razaoSocial) values(?, ?, ?)",
              array($idCliente, $document, $name));
          break;
      }
      
      $db->close(true);
    }
    catch(DBError $e) {
      $db->close(false);
      logMessage($e->errors, "DBError");
      return "Falha no banco de dados. O erro foi reportado.";
    }
    
    return true;
    
    invalidDocument:
    $this->fields[ClientCreate::$documentField]->setValid(false);
    
    if(isset($db)) {
      $db->close(false);
    }
    
    return $out;
  }
  
}

$page = new Page("Cadastro de Cliente");
$clientCreate = new ClientCreate();
$form = new StdForm($clientCreate, $_GET, $_POST,
        "<p>" . htmlentities("Campos em negrito são obrigatórios. Seu e-mail será usado como login.") . "</p>",
        "<p>" . htmlentities("Cadastro realizado com sucesso. Agora você pode fazer logar no sistema.") . "</p>",
        "ClientCreate.php");
$form->processForm();
$page->addContent($form->getHtml());
echo $page->getHtml();
